
#include <tftpserver.hpp>
#include <arpa/inet.h>
#include <sys/un.h>

#define LISTEN_BACKLOG  (20)
void usage(char *argv)
{
    printf("usage: %s [port]\n",argv);
    printf("       port - default %d\n",TFTP_SERVER_PORT);
}

int main(int argc,char *argv[])
{
    usage(argv[0]);

    uint16_t port = TFTP_SERVER_PORT;
    if(2 <= argc)
    {
        port = (uint16_t)atoi(argv[1]);
    }

    int sock =socket(AF_INET, SOCK_DGRAM, 0);
    if(0 > sock)
    {
        printf("Server socket could not be created(ret=%d)\n",sock);
        perror("socket ");
		return -1;
	}

    struct sockaddr_in svr;
    uint32_t svrlen = sizeof(svr);
    bzero(&svr,sizeof(svr));
    svr.sin_family = AF_INET;
	svr.sin_addr.s_addr = INADDR_ANY;
	svr.sin_port = htons(port);
    int on = 1;
    /**<  利用setsockopt避免bind出错的情况 */
    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    int ret = bind(sock,(struct sockaddr*)&svr,svrlen);
	if(0 > ret)
    {
        printf("bind to port %d fail(ret=%d)\n",port,ret);
        perror("bind ");
		return -2;
	}
    
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    tftp_request_packet_s request;

    tftp_agent *docker = nullptr;
    do
    {
        ret = recvfrom(sock,&request,sizeof(request),0,(struct sockaddr*)&client,&len);
        if(0 < ret)
        {
            printf("receved data from %s port %d\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));
            if((tftp_cmd_rrq==ntohs(request.opcode) || tftp_cmd_wrq==ntohs(request.opcode))
                && (ret>5))
            {
                printf("tftp request(cmd=%d,filename=%s) \n",ntohs(request.opcode),request.filemsg);
                docker = new tftp_agent(request,sock,client);
            }
        }
    }while(1);
    
    return 0;
}